<template>
  <el-row class="mx__20 px-20 bg-white">
    <el-col class="current-content-style">
      <el-row class="py-20">
        <el-col :span="12">
          <div>
            <el-button type="primary" plain @click="modalVisible = true">添加角色</el-button>
          </div>
          <el-table
            :data="tableData"
            style="width: 100%"
            class="mt-20"
            :header-row-class-name="
              ({ row, rowIndex }) => {
                if (rowIndex === 0) return 'table-header-bg'
              }
            "
          >
            <el-table-column type="index" width="80" label="序号"> </el-table-column>
            <el-table-column prop="roleTitle" label="标识符"> </el-table-column>
            <el-table-column prop="roleName" label="角色名称"> </el-table-column>
            <el-table-column label="操作" width="200">
              <template v-slot="scope">
                <i @click="editPermission(scope.row)" class="mr-20 curser-pointer text-primary el-icon-info"
                  >授权管理</i
                >

                <el-popconfirm
                  v-if="scope.row.roleName !== '系统管理员'"
                  confirm-button-text="删除"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定要删除这个角色吗？"
                  @confirm="deleteRolesFn(scope.row)"
                >
                  <i slot="reference" class="curser-pointer text-warning el-icon-delete">删除</i>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-col>

    <!-- 添加角色模态框 -->
    <el-dialog
      :destory-on-close="true"
      title="添加角色"
      :visible.sync="modalVisible"
      width="30%"
      @close="handler_close"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName" placeholder="请输入中文角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色标识" prop="roleTitle">
          <el-input v-model="ruleForm.roleTitle" placeholder="请输入英文标识"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="modalVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAccountFn('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看权限，编辑权限 -->
    <el-dialog
      :destory-on-close="true"
      title="查看、编辑角色权限"
      :visible.sync="modalVisible2"
      width="30%"
      @close="handler_close2"
    >
      <el-form :model="ruleForm2" ref="ruleFormPermission" label-width="0px">
        <el-checkbox-group v-model="checkList">
          <div class="permission-row" v-for="item in menu" :key="item.menuId">
            <!-- indeterminate:true,表示全选这类菜单，false,全不选 -->
            <el-checkbox :label="item.menuId" @change="checked => checkPermission_1(item.menuId, checked)">{{
              item.menuTitle
            }}</el-checkbox>
            <div>
              <el-checkbox
                :label="el.menuId"
                v-for="el in item.children"
                :key="el.menuId"
                @change="checked => checkPermission_1(el.menuId, checked)"
                >{{ el.menuTitle }}</el-checkbox
              >
            </div>
          </div>
        </el-checkbox-group>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="modalVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="editPermissontFn">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
import { getRoleAll, addRole, deleteRole, findRolePermissionById, updatePermission } from '../config/api'
export default {
  data() {
    return {
      editStatus: false, //权限是否被修改个状态
      roleId: undefined,
      checkList: [],
      menu: [],
      modalVisible: false,
      modalVisible2: false,
      tableData: [],
      ruleForm2: {}, // 权限表单
      ruleForm: {
        // 添加角色表单
        roleName: '',
        roleTitle: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个中文字符', trigger: 'blur' }
        ],
        roleTitle: [
          { required: true, message: '请输入角色标识', trigger: 'blur' },
          { min: 1, max: 20, pattern: /^\w{1,20}$/, message: '长度在 1 到 20 个英文字符', trigger: 'blur' }
        ]
      },
      permissonData: [] //所有权限
    }
  },
  created() {
    this.getRoleAllFn()
  },
  computed: {
    checkPermission(roleId) {
      let flag = false
      this.permissonData.forEach(item => {
        if (item.menuId === roleId) {
          flag = item.checked
        }
      })
      return flag
    }
  },
  methods: {
    // 编辑权限,并掉接口
    editPermissontFn() {
      // console.log(this.checkList)
      if (!this.editStatus) {
        this.modalVisible2 = false
        return
      }
      updatePermission({ menuIdArr: this.checkList || null, roleId: this.roleId }).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: '授权成功',
            type: 'success'
          })
          this.editStatus = false
        } else {
          this.$message({
            message: '授权失败',
            type: 'error'
          })
        }
        this.modalVisible2 = false
      })
    },
    // 全选或全不选子项
    checkPermission_1(menuId, checked) {
      // console.log(menuId, checked)
      this.editStatus = true
      let menuParentId
      this.permissonData.forEach(item => {
        // 修改当前的选中状态值
        if (item.menuId === menuId) {
          item.checked = checked
          menuParentId = item.menuParent
        }
      })

      // 如果是大类权限，直接改子类权限
      if (menuParentId === null) {
        // 判断是否要全选，全不选一个大类的权限
        this.permissonData.forEach(el => {
          if (el.menuParent === menuId) {
            el.checked = checked
          }
        })
      } else {
        // 下面判断小类权限的改变
        // 1. 拿到同类子权限
        let someSubPermissonArr = this.permissonData.filter(el => el.menuParent === menuParentId)
        // 2. 统计全选或全不选数量
        let inChecked = 0,
          outChecked = 0
        someSubPermissonArr.forEach(el => {
          if (el.checked === true) {
            inChecked++
          } else {
            outChecked++
          }
        })
        // 3 改父级权限状态
        if (inChecked === someSubPermissonArr.length) {
          this.permissonData.find(el => el.menuId == menuParentId).checked = true
        }
        if (outChecked === someSubPermissonArr.length)
          this.permissonData.find(el => el.menuId == menuParentId).checked = false
      }

      this.checkList = []
      this.permissonData.forEach(el => {
        if (el.checked === true) {
          this.checkList.push(el.menuId)
        }
      })
    },
    // 获取所有角色
    getRoleAllFn() {
      getRoleAll().then(res => {
        if (res.code === 200) {
          this.tableData = res.data
        }
      })
    },
    // 删除角色
    deleteRolesFn({ roleTitle, roleId }) {
      console.log(roleId)
      if (roleTitle === 'system') {
        this.$message({
          type: 'warning',
          message: '系统管理员不可以删除'
        })
        return
      }
      deleteRole({ roleId }).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除角色成功'
          })
          this.getRoleAllFn()
        } else {
          this.$message({
            type: 'success',
            message: '删除角色失败'
          })
        }
      })
    },
    // 添加角色
    addAccountFn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addRole(this.ruleForm).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '添加角色成功'
              })
              this.getRoleAllFn()
              this.modalVisible = false
            } else {
              this.$message({
                type: 'error',
                message: '添加角色失败'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 编辑，查看权限
    async editPermission(row) {
      // console.log(row)
      this.roleId = row.roleId
      let arrMenu = JSON.parse(JSON.stringify(this.$store.state.menu))

      arrMenu.forEach(el => {
        let arr = el.children
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i]
          if (item.menuType == 2) {
            console.log(item.menuTitle)
            arr.splice(i, 1)
            i--
          }
        }
      })

      this.menu = arrMenu
      // 获取这个角色的所有权限
      await findRolePermissionById({ roleId: row.roleId }).then(res => {
        if (res.code === 200) {
          console.log(res.data)
          res.data.forEach(el => {
            // 添加默认选中的权限
            if (el.checked) {
              this.checkList.push(el.menuId)
            }
          })
          console.log(this.checkList)
          this.modalVisible2 = true
          this.permissonData = res.data
        }
      })
      console.log('角色拥有的权限', this.permissonData)
    },
    handler_close() {
      this.$refs['ruleForm'].resetFields()
      this.checkList = []
    },
    handler_close2() {
      this.$refs['ruleFormPermission'].resetFields()
      this.checkList = []
    }
  }
}
</script>

<style>
.permission-row {
  line-height: 40px;
  border-bottom: 1px solid rgba(207, 203, 203, 0.719);
}
</style>
